package com.yiren.manager.ctrl.cost;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBeHospitalPledge;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderOutOrder;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrElderWalletRechargeRecord;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrOutFeeRecord;
import com.yiren.entity.YrPaper;
import com.yiren.entity.YrPaperRecord;
import com.yiren.entity.YrStaffInfo;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.cost.YrOutFeeRecordForm;
import com.yiren.manager.form.cost.YrPaperRecordForm;
import com.yiren.manager.form.department.YrStaffInfoForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.service.iface.cost.YrElderWalletRechargeRecordService;
import com.yiren.manager.service.iface.cost.YrOutFeeRecordService;
import com.yiren.manager.service.iface.cost.YrPaperRecordService;
import com.yiren.manager.service.iface.cost.YrPaperService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderOutOrderService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.lease.YrBeHospitalPledgeService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("paperRecord")
@RestController
public class YrPaperRecordController extends GenericController<YrPaperRecordForm, YrPaperRecord> {

	@Autowired
	private YrPaperRecordService selfSevice;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrPaperService paperService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrOutFeeRecordService outFeeRecordService;

	@Autowired
	private YrElderWalletRechargeRecordService elderWalletRechargeRecordService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrMealCardService mealCardService;
	
	@Autowired
	private YrBeHospitalPledgeService beHospitalPledgeService;
	
	@Autowired
	private YrElderOutOrderService elderOutOrderService;
	
	/**
	 * 保存一个票据
	 * 
	 * @param data
	 * @return
	 * @throws MyException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 * @throws SwallowException
	 */
	@RequestMapping("save")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> save(String data) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, SwallowException {
		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrPaperRecordForm form = tool.mapper("paperRecord", YrPaperRecordForm.class);

		if (null == form) {
			throwExp("param.error");
		}

		String sqlWhere = "relation_id=?1 AND paper_type=?2";
		QueryResult<YrPaperRecord> qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere,
				new Object[] { form.getRelationId(), form.getPaperType() });
		if (!qrPaperRecord.getResultList().isEmpty()) {
			throwExp("该数据已经打印，请勿重复打印");
		}
		YrPaperRecord entity = ObjectUtils.objectToObject(form, YrPaperRecord.class);
		if (null == form.getPaperRecordId() || form.getPaperRecordId().isEmpty()) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
			entity.setCreateTime(new Date());
			entity.setPaperRecordId(UUIDGenerator.getUUID());
			entity.setRelationId(entity.getRelationId() + "=" + sdf.format(entity.getCreateTime()));
			entity.setStatus(0);
		}
		sqlWhere = "paper_type=?1 AND staff_id=?2 AND batch_num=?3";
		Integer paperType = entity.getPaperType();
		if (entity.getPaperType() == 5) {// 如果是出院的则查询票据类型为3的票据号码
			paperType = 3;
		}
		QueryResult<YrPaper> qrPaper = paperService.find(YrPaper.class, sqlWhere,
				new Object[] { paperType, entity.getStaffId(), entity.getBatchNum() });
		if (qrPaper.getResultList().isEmpty()) {
			throwExp("所需票据不存在");
		}
		YrPaper paper = qrPaper.getResultList().get(0);
		paper.setUseNum(toNumberStr(paper.getUseNum()));
		entity.setUpdateTime(new Date());
		entity.setPrintDate(new Date());
		selfSevice.save(entity);
		paperService.save(paper);

		return result;
	}

	/**
	 * 获取当前的票据号
	 * 
	 * @param relationId
	 *            关系id
	 * @param paperPype
	 *            票据类型（1发票2预交款收据3收费凭据）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getUserPaperByRelationId")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> getUserPaperByRelationId(String relationId, Integer paperType)
			throws Exception {
		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();
		if (null == relationId) {
			throwExp("param.error");
		}
		String sqlWhere;
		QueryResult<YrPaperRecord> qrPaper;
		if (null == paperType) {
			sqlWhere = "relation_id=?1 AND status=0";
			qrPaper = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { relationId });
		} else {
			sqlWhere = "relation_id=?1 AND paper_type=?2 AND status=0";
			qrPaper = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { relationId, paperType });
		}

		List<YrPaperRecordForm> formList = new ArrayList<>();

		for (YrPaperRecord paper : qrPaper.getResultList()) {
			YrPaperRecordForm paperForm = toForm(paper);
			YrStaffInfo staffInfo = staffInfoService.findOne(paper.getStaffId());
			if (null != staffInfo) {
				paperForm.setStaffInfoForm(ObjectUtils.objectToObject(staffInfo, YrStaffInfoForm.class));
			}
			formList.add(paperForm);
		}
		result.setData(formList);

		return result;
	}

	public static String toNumberStr(String pagerNum) {
		int length = pagerNum.length();
		int num = Integer.parseInt(pagerNum) + 1;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			if (pagerNum.charAt(i) == '0') {
				sb.append('0');
			} else {
				break;
			}
		}
		return sb.append(num).toString();
	}

	/**
	 * 票据作废
	 * 
	 * @param id
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("invalid")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> invalid(String id) throws MyException {

		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();

		if (null == id) {
			throwExp("param.error");
		}
		YrPaperRecord paperRecord = selfSevice.findOne(id);
		if (null == paperRecord) {
			throwExp("查询不到相应的票据信息");
		}
		if (paperRecord.getPaperType() == 2) {// 如果是预交款票据
			String sqlWhere = "CONCAT(elder_wallet_recharge_record_id,'-walletRecharge')=?1";
			QueryResult<YrElderWalletRechargeRecord> qrElderWalletRechargeRecord = elderWalletRechargeRecordService
					.find(YrElderWalletRechargeRecord.class, sqlWhere, new Object[] { paperRecord.getRelationId() });
			if (qrElderWalletRechargeRecord.getResultList().isEmpty()) {
				throwExp("查询不到相关缴费记录");
			}
			// 删除缴费记录并减掉钱包的钱
			YrElderWalletRechargeRecord elderWalletRechargeRecord = qrElderWalletRechargeRecord.getResultList().get(0);
			sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { elderWalletRechargeRecord.getElderId() });
			if (qrElderWallet.getResultList().isEmpty()) {
				throwExp("查询不到相关的钱包信息");
			}
			YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
			elderWallet.setWalletBalance(elderWallet.getWalletBalance() - elderWalletRechargeRecord.getRechargeMoney());

			elderWalletRechargeRecordService.delete(elderWalletRechargeRecord);
			elderWalletService.save(elderWallet);
		} else if (paperRecord.getPaperType() == 5) {// 如果是缴费收据
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(paperRecord.getBeHospitalId());
			if(null==elderBeHospital){
				throwExp("查询不到相关的住院登记信息");
			}
			elderBeHospital.setBeStatus(1);//设置为正在出院状态
			String sqlWhere = "be_hospital_id=?1";
			LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			map.put("createTime", "DESC");
			QueryResult<YrOutFeeRecord> qrOutFeeRecord = outFeeRecordService.find(YrOutFeeRecord.class, sqlWhere, new Object[]{paperRecord.getBeHospitalId()},map);
			if(qrOutFeeRecord.getResultList().isEmpty()){
				throwExp("查询不到相关的出院费用结清记录");
			}
			YrOutFeeRecord outFeeRecord = qrOutFeeRecord.getResultList().get(0);
			YrElder elder = elderService.findOne(elderBeHospital.getElderId());
			if(null==elder){
				throwExp("查询不到相关的老者信息");
			}
			//恢复钱包
			sqlWhere = "elder_id=?1";
			YrElderWallet elderWallet = null;
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere, new Object[]{elder.getElderId()});
			if(qrElderWallet.getTotalRecord()>0){
				elderWallet = qrElderWallet.getResultList().get(0);
				elderWallet.setWalletBalance(elderWallet.getWalletBalance()+outFeeRecord.getMoneyWallet());
			}
			//恢复饭卡
			sqlWhere = "card_card_id=?1";
			YrMealCard mealCard = null;
			QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere, new Object[]{elder.getCardId()});
			if(qrMealCard.getTotalRecord()>0){
				mealCard = qrMealCard.getResultList().get(0);
				mealCard.setBalance(mealCard.getBalance()+outFeeRecord.getMoneyMealCard());
			}
			//恢复押金
			sqlWhere = "be_hospital_id=?1";
			List<YrBeHospitalPledge> beHospitalPledges = new ArrayList<YrBeHospitalPledge>();
			QueryResult<YrBeHospitalPledge> qrBeHospitalPledge = beHospitalPledgeService.find(YrBeHospitalPledge.class, sqlWhere, new Object[]{elderBeHospital.getBeHospitalId()});
			for(YrBeHospitalPledge entity : qrBeHospitalPledge.getResultList()){
				entity.setStatus(0);
				entity.setReturnTime(null);
				beHospitalPledges.add(entity);
			}
			sqlWhere = "be_hospital_id=?1 AND status=2";
			QueryResult<YrElderOutOrder> qrElderOutOrder = elderOutOrderService.find(YrElderOutOrder.class, sqlWhere, new Object[]{elderBeHospital.getBeHospitalId()});
			List<YrElderOutOrder> elderOutOrders = new ArrayList<YrElderOutOrder>();
			for(YrElderOutOrder elderOutOrder : qrElderOutOrder.getResultList()){
				elderOutOrder.setStatus(0);//设置为正在出院状态
				elderOutOrder.setUpdateId("-1");
				elderOutOrder.setUpdateTime(new Date());
				elderOutOrders.add(elderOutOrder);
			}
			elderBeHospitalService.save(elderBeHospital);
			elderWalletService.save(elderWallet);
			mealCardService.save(mealCard);
			for(YrBeHospitalPledge beHospitalPledge : beHospitalPledges){
				beHospitalPledgeService.save(beHospitalPledge);
			}
			for(YrElderOutOrder elderOutOrder : elderOutOrders){
				elderOutOrderService.save(elderOutOrder);
			}
			outFeeRecordService.delete(outFeeRecord);
		}
		paperRecord.setInvalidTime(new Date());
		paperRecord.setStatus(1);// 设置为作废
		selfSevice.save(paperRecord);
		return result;
	}

	/**
	 * 查找票据
	 * 
	 * @param staffId
	 * @param paperType
	 * @param searhVal
	 * @return
	 * @throws MyException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> find(String staffId, Integer paperType, String searhVal) throws MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();

		if (null == staffId || paperType == null || searhVal == null) {
			throwExp("param.error");
		}

		String sqlWhere = "staff_id=?1 AND paper_type=?2 AND paper_num=?3 AND status=0";

		QueryResult<YrPaperRecord> qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere,
				new Object[] { staffId, paperType, searhVal });

		List<YrPaperRecordForm> formList = new ArrayList<YrPaperRecordForm>();
		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			YrPaperRecordForm form = ObjectUtils.objectToObject(paperRecord, YrPaperRecordForm.class);
			YrStaffInfo staffInfo = staffInfoService.findOne(paperRecord.getStaffId());
			if (null != staffInfo) {
				form.setStaffInfoForm(ObjectUtils.objectToObject(staffInfo, YrStaffInfoForm.class));
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	/**
	 * 日报表
	 * 
	 * @param staffId
	 * @param printDate
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("getDayPaperReportForm")
	@ResponseBody
	public HTTPResult<DayPaperReportForm> getDayPaperReportForm(String staffId, String printDate) throws MyException {

		HTTPResult<DayPaperReportForm> result = new HTTPResult<DayPaperReportForm>();

		String sqlWhere = "staff_id=?1 AND ((DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND STATUS=0) OR "
				+ "DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND DATE_FORMAT(print_date,'%Y-%m-%d')<>DATE_FORMAT(invalid_time,'%Y-%m-%d') AND STATUS=1) AND paper_type=5 ";
		QueryResult<YrPaperRecord> qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere,
				new Object[] { staffId, printDate });

		Float totalAmount = 0F;
		Long count = qrPaperRecord.getTotalRecord();

		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			totalAmount += paperRecord.getAmount();
		}

		Set<PaperNumFrom> paperNumForms = getPaperNumFroms(qrPaperRecord.getResultList());

		SettlePaperForm settlePaperForm = new SettlePaperForm();
		settlePaperForm.setCount(count);
		settlePaperForm.setPaperNumForms(paperNumForms);
		settlePaperForm.setTotalAmount(totalAmount);

		sqlWhere = "staff_id=?1 AND ((DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND STATUS=0) OR "
				+ "DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND DATE_FORMAT(print_date,'%Y-%m-%d')<>DATE_FORMAT(invalid_time,'%Y-%m-%d') AND STATUS=1) AND paper_type=2 ";
		qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { staffId, printDate });

		count = qrPaperRecord.getTotalRecord();
		totalAmount = 0F;

		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			totalAmount += paperRecord.getAmount();
		}

		paperNumForms = getPaperNumFroms(qrPaperRecord.getResultList());

		PlanPaperForm planPaperForm = new PlanPaperForm();
		planPaperForm.setCount(count);
		planPaperForm.setPaperNumForms(paperNumForms);
		planPaperForm.setTotalAmount(totalAmount);

		sqlWhere = "staff_id=?1 AND ((DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND STATUS=0) OR "
				+ "DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND DATE_FORMAT(print_date,'%Y-%m-%d')<>DATE_FORMAT(invalid_time,'%Y-%m-%d') AND STATUS=1) AND paper_type=3";
		qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { staffId, printDate });

		count = qrPaperRecord.getTotalRecord();
		totalAmount = 0F;

		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			totalAmount += paperRecord.getAmount();
		}

		paperNumForms = getPaperNumFroms(qrPaperRecord.getResultList());

		ChargePaperFrom chargePaperFrom = new ChargePaperFrom();
		chargePaperFrom.setCount(count);
		chargePaperFrom.setPaperNumForms(paperNumForms);
		chargePaperFrom.setTotalAmount(totalAmount);

		sqlWhere = "staff_id=?1 AND paper_type=5 AND ((STATUS=0 AND DATE_FORMAT(print_date,'%Y-%m-%d')=?2) OR "
				+ "DATE_FORMAT(print_date,'%Y-%m-%d')=?2 AND DATE_FORMAT(print_date,'%Y-%m-%d')<>DATE_FORMAT(invalid_time,'%Y-%m-%d') AND STATUS=1)";
		qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { staffId, printDate });

		count = qrPaperRecord.getTotalRecord();
		totalAmount = 0F;
		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			totalAmount += paperRecord.getTotalPay() + paperRecord.getPledge();
		}

		// paperNumForms = getPaperNumFroms(qrPaperRecord.getResultList());
		paperNumForms = new HashSet<PaperNumFrom>();

		ReturnPaperForm returnPaperForm = new ReturnPaperForm();
		returnPaperForm.setCount(count);
		returnPaperForm.setPaperNumForms(paperNumForms);
		returnPaperForm.setTotalAmount(totalAmount);

		InvalidPaperForm invalidPaperForm = new InvalidPaperForm();

		sqlWhere = "staff_id=?1 AND (DATE_FORMAT(print_date,'%Y-%m-%d')=?2 OR DATE_FORMAT(invalid_time,'%Y-%m-%d')=?2) AND paper_type=5 AND STATUS=1";
		qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { staffId, printDate });

		List<String> settlePaperNumers = new ArrayList<>();

		List<String> payPaperNumbers = new ArrayList<>();

		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			settlePaperNumers.add(paperRecord.getPaperNum());
		}

		sqlWhere = "staff_id=?1 AND (DATE_FORMAT(print_date,'%Y-%m-%d')=?2 OR DATE_FORMAT(invalid_time,'%Y-%m-%d')=?2) AND (paper_type=2 OR paper_type=3) AND STATUS=1";
		qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere, new Object[] { staffId, printDate });
		for (YrPaperRecord paperRecord : qrPaperRecord.getResultList()) {
			payPaperNumbers.add(paperRecord.getPaperNum());
		}
		invalidPaperForm.setSettlePaperNumers(settlePaperNumers);
		invalidPaperForm.setPayPaperNumbers(payPaperNumbers);
		DayPaperReportForm dayPaperReportForm = new DayPaperReportForm();
		dayPaperReportForm.setSettlePaperForm(settlePaperForm);
		dayPaperReportForm.setPlanPaperForm(planPaperForm);
		dayPaperReportForm.setReturnPaperForm(returnPaperForm);
		dayPaperReportForm.setInvalidPaperForm(invalidPaperForm);
		dayPaperReportForm.setChargePaperFrom(chargePaperFrom);

		List<DayPaperReportForm> formList = new ArrayList<>();
		formList.add(dayPaperReportForm);

		result.setData(formList);
		return result;

	}

	@RequestMapping("findAllPaperReportByPaperType")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> findAllPaperReportByPaperType(String dateSince, String dateEnd,
			Integer paperType) throws MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();

		String sqlWhere = "DATE_FORMAT(print_date,'%Y-%m-%d')>=?1 AND DATE_FORMAT(print_date,'%Y-%m-%d')<=?2 AND paper_type=?3 AND status=0";

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("paperNum", "ASC");

		QueryResult<YrPaperRecord> qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere,
				new Object[] { dateSince, dateEnd, paperType }, map);

		result.setData(setPaperRecordForms(qrPaperRecord.getResultList(), paperType));
		return result;
	}

	@RequestMapping("findPaperReportByPaperType")
	@ResponseBody
	public HTTPResult<YrPaperRecordForm> findPaperReportByPaperType(String date, Integer paperType, String staffId)
			throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		HTTPResult<YrPaperRecordForm> result = new HTTPResult<YrPaperRecordForm>();

		String sqlWhere = "DATE_FORMAT(print_date,'%Y-%m-%d')=?1 AND paper_type=?2 AND staff_id=?3 AND status=0";

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("paperNum", "ASC");

		QueryResult<YrPaperRecord> qrPaperRecord = selfSevice.find(YrPaperRecord.class, sqlWhere,
				new Object[] { date, paperType, staffId }, map);

		result.setData(setPaperRecordForms(qrPaperRecord.getResultList(), paperType));
		return result;
	}

	private List<YrPaperRecordForm> setPaperRecordForms(List<YrPaperRecord> paperRecords, Integer paperType)
			throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {

		String sqlWhere = "be_hospital_id=?1";

		List<YrPaperRecordForm> formList = new ArrayList<YrPaperRecordForm>();
		for (YrPaperRecord paperRecord : paperRecords) {
			YrPaperRecordForm form = ObjectUtils.objectToObject(paperRecord, YrPaperRecordForm.class);
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(paperRecord.getBeHospitalId());
			if (null != elderBeHospital) {
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital,
						YrElderBeHospitalForm.class);
				form.setElderBeHospitalForm(elderBeHospitalForm);
				YrElder elder = elderService.findOne(elderBeHospital.getElderId());
				if (null != elder) {
					YrElderForm elderForm = ObjectUtils.objectToObject(elder, YrElderForm.class);
					elderBeHospitalForm.setElderForm(elderForm);
				}
			}
			YrStaffInfo staffInfo = staffInfoService.findOne(paperRecord.getStaffId());
			if (null != staffInfo) {
				form.setStaffInfoForm(ObjectUtils.objectToObject(staffInfo, YrStaffInfoForm.class));
			}
			if (paperType == 5) {
				QueryResult<YrOutFeeRecord> qrOutFeeRecord = outFeeRecordService.find(YrOutFeeRecord.class, sqlWhere,
						new Object[] { elderBeHospital.getBeHospitalId() });
				if (!qrOutFeeRecord.getResultList().isEmpty()) {
					form.setOutFeeRecordForm(ObjectUtils.objectToObject(qrOutFeeRecord.getResultList().get(0),
							YrOutFeeRecordForm.class));
				}
			}
			formList.add(form);
		}
		return formList;
	}

	public Set<PaperNumFrom> getPaperNumFroms(List<YrPaperRecord> paperRecords) {
		Map<String, PaperNumFrom> mapPaperNum = new HashMap<String, PaperNumFrom>();
		Set<PaperNumFrom> paperNumForms = new HashSet<PaperNumFrom>();

		for (YrPaperRecord paperRecord : paperRecords) {

			PaperNumFrom paperNumFrom = mapPaperNum.get(paperRecord.getBatchNum());
			if (null == paperNumFrom) {
				paperNumFrom = new PaperNumFrom();
				paperNumFrom.setStartNum(paperRecord.getPaperNum());
				paperNumFrom.setEndNum(paperRecord.getPaperNum());
			} else {
				paperNumFrom.setStartNum(
						Long.parseLong(paperRecord.getPaperNum()) < Long.parseLong(paperNumFrom.getStartNum())
								? paperRecord.getPaperNum() : paperNumFrom.getStartNum());
				paperNumFrom
						.setEndNum(Long.parseLong(paperRecord.getPaperNum()) > Long.parseLong(paperNumFrom.getEndNum())
								? paperRecord.getPaperNum() : paperNumFrom.getEndNum());
			}
			mapPaperNum.put(paperRecord.getBatchNum(), paperNumFrom);
		}
		for (Map.Entry<String, PaperNumFrom> entry : mapPaperNum.entrySet()) {
			paperNumForms.add(entry.getValue());
		}

		return paperNumForms;
	}

	/**
	 * 结算日报表
	 * 
	 * @author yan
	 *
	 */
	private class DayPaperReportForm {
		private SettlePaperForm settlePaperForm; // 结算发票
		private PlanPaperForm planPaperForm;// 收预缴金
		private ReturnPaperForm returnPaperForm;// 退预缴金
		private ChargePaperFrom chargePaperFrom;// 收费凭据

		public ChargePaperFrom getChargePaperFrom() {
			return chargePaperFrom;
		}

		public void setChargePaperFrom(ChargePaperFrom chargePaperFrom) {
			this.chargePaperFrom = chargePaperFrom;
		}

		public ReturnPaperForm getReturnPaperForm() {
			return returnPaperForm;
		}

		public void setReturnPaperForm(ReturnPaperForm returnPaperForm) {
			this.returnPaperForm = returnPaperForm;
		}

		private InvalidPaperForm invalidPaperForm;// 作废票据

		public SettlePaperForm getSettlePaperForm() {
			return settlePaperForm;
		}

		public void setSettlePaperForm(SettlePaperForm settlePaperForm) {
			this.settlePaperForm = settlePaperForm;
		}

		public PlanPaperForm getPlanPaperForm() {
			return planPaperForm;
		}

		public void setPlanPaperForm(PlanPaperForm planPaperForm) {
			this.planPaperForm = planPaperForm;
		}

		public InvalidPaperForm getInvalidPaperForm() {
			return invalidPaperForm;
		}

		public void setInvalidPaperForm(InvalidPaperForm invalidPaperForm) {
			this.invalidPaperForm = invalidPaperForm;
		}

	}

	private class PaperNumFrom {
		private String startNum;
		private String endNum;

		public String getStartNum() {
			return startNum;
		}

		public void setStartNum(String startNum) {
			this.startNum = startNum;
		}

		public String getEndNum() {
			return endNum;
		}

		public void setEndNum(String endNum) {
			this.endNum = endNum;
		}

		@Override
		public boolean equals(Object o) {
			if (this == o)
				return true;
			if (o == null || getClass() != o.getClass())
				return false;
			PaperNumFrom user = (PaperNumFrom) o;
			return Objects.equals(startNum, user.startNum) && Objects.equals(user.endNum, endNum);
		}

		@Override
		public int hashCode() {
			return Objects.hash(startNum, endNum);
		}
	}

	/**
	 * 结算发票
	 * 
	 * @author yan
	 *
	 */
	private class SettlePaperForm {
		private Float totalAmount;
		private Long count;
		private Set<PaperNumFrom> paperNumForms;

		public Float getTotalAmount() {
			return totalAmount;
		}

		public void setTotalAmount(Float totalAmount) {
			this.totalAmount = totalAmount;
		}

		public Long getCount() {
			return count;
		}

		public void setCount(Long count) {
			this.count = count;
		}

		public Set<PaperNumFrom> getPaperNumForms() {
			return paperNumForms;
		}

		public void setPaperNumForms(Set<PaperNumFrom> paperNumForms) {
			this.paperNumForms = paperNumForms;
		}

	}

	/**
	 * 收费凭据
	 * 
	 * @author yan
	 *
	 */
	private class ChargePaperFrom {
		private Float totalAmount;
		private Long count;
		private Set<PaperNumFrom> paperNumForms;

		public Float getTotalAmount() {
			return totalAmount;
		}

		public void setTotalAmount(Float totalAmount) {
			this.totalAmount = totalAmount;
		}

		public Long getCount() {
			return count;
		}

		public void setCount(Long count) {
			this.count = count;
		}

		public Set<PaperNumFrom> getPaperNumForms() {
			return paperNumForms;
		}

		public void setPaperNumForms(Set<PaperNumFrom> paperNumForms) {
			this.paperNumForms = paperNumForms;
		}

	}

	/**
	 * 收预缴金发票
	 * 
	 * @author yan
	 *
	 */
	private class PlanPaperForm {
		private Float totalAmount;
		private Long count;
		private Set<PaperNumFrom> paperNumForms;

		public Float getTotalAmount() {
			return totalAmount;
		}

		public void setTotalAmount(Float totalAmount) {
			this.totalAmount = totalAmount;
		}

		public Long getCount() {
			return count;
		}

		public void setCount(Long count) {
			this.count = count;
		}

		public Set<PaperNumFrom> getPaperNumForms() {
			return paperNumForms;
		}

		public void setPaperNumForms(Set<PaperNumFrom> paperNumForms) {
			this.paperNumForms = paperNumForms;
		}
	}

	/**
	 * 作废票据
	 * 
	 * @author yan
	 *
	 */
	private class InvalidPaperForm {

		private List<String> settlePaperNumers;

		private List<String> payPaperNumbers;

		public List<String> getSettlePaperNumers() {
			return settlePaperNumers;
		}

		public void setSettlePaperNumers(List<String> settlePaperNumers) {
			this.settlePaperNumers = settlePaperNumers;
		}

		public List<String> getPayPaperNumbers() {
			return payPaperNumbers;
		}

		public void setPayPaperNumbers(List<String> payPaperNumbers) {
			this.payPaperNumbers = payPaperNumbers;
		}
	}

	/**
	 * 退预缴金发票
	 * 
	 * @author yan
	 *
	 */
	private class ReturnPaperForm {
		private Float totalAmount;
		private Long count;
		private Set<PaperNumFrom> paperNumForms;

		public Float getTotalAmount() {
			return totalAmount;
		}

		public void setTotalAmount(Float totalAmount) {
			this.totalAmount = totalAmount;
		}

		public Long getCount() {
			return count;
		}

		public void setCount(Long count) {
			this.count = count;
		}

		public Set<PaperNumFrom> getPaperNumForms() {
			return paperNumForms;
		}

		public void setPaperNumForms(Set<PaperNumFrom> paperNumForms) {
			this.paperNumForms = paperNumForms;
		}

	}

	@Override
	public YrPaperRecordForm toForm(YrPaperRecord e) throws Exception {
		YrPaperRecordForm form = ObjectUtils.objectToObject(e, YrPaperRecordForm.class);
		return form;
	}

	@Override
	public YrPaperRecord toEntity(YrPaperRecordForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
